package com.lwy.demo.serivce;


import com.lwy.demo.dao.UserMapper;
import com.lwy.demo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@Transactional
public class UserService {

    private final static String CACHE_KEY_USER = "user:";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper mapper;
    //插入
    public void addUser(User user){
        //先插入mysql
        int i = mapper.insertUser(user);
        //成功插入 再查redis
        if(i>0)
        {
            //再次查询mysql 看看是否插入进去 保证数据库安全
            User user1 = mapper.selectUser(user.getId());
            //设置key
            String key = CACHE_KEY_USER + user1.getId();
            //存入redis
            redisTemplate.opsForValue().set(key,user1);
        }

    }
    //修改
    public void updateUser(User user){
        //先修改mysql
        int i = mapper.updateUser(user);
        if(i>0){
            //查询
            User user1 = mapper.selectUser(user.getId());
            String key = CACHE_KEY_USER + user.getId();
            //redis
            redisTemplate.opsForValue().set(key,user1);
        }
    }
    //删除
    public void deleteUser(Integer id){
        int i = mapper.deleteUser(id);
        if(i >0){
            //设置key
            String key = CACHE_KEY_USER + id;
            //删除
            redisTemplate.delete(key);
        }
    }
    //查询 大厂 双端检索
    public User selectUser(Integer id){
        //设置key
        String key = CACHE_KEY_USER + id;
        //先去redis查询
        User user = (User) redisTemplate.opsForValue().get(key);
            if(user == null){
                synchronized (UserService.class){   //防止击穿mysql
                    //二次查询 redis
                    if(user == null){
                        //去mysql 那
                        user = mapper.selectUser(id);
                        if(user == null){
                            return user;
                        }
                        else {
                            //存入redis
                            redisTemplate.opsForValue().setIfAbsent(key,user,7L, TimeUnit.DAYS);
                        }
                    }
                }
            }

            return user;
    }
}
